package impl.defaultImpl;

import design.Input;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Scanner;

/**
 * @ClassName DocxFileInput .java
 * @Description empty
 * @Author LiuJinyu
 * @Date 2023/4/2 19:01
 * @Version 1.0
 */

public class DefaultDocxFileInput extends Input {
    private static final Logger logger = LogManager.getLogger(DefaultDocxFileInput.class);
    private File docxFile;
    private Scanner scanner;

    private XWPFDocument docx;

    public DefaultDocxFileInput(){
        scanner = new Scanner(System.in);
    }

    @Override
    public void input() {
        System.out.print("请输入文件的完整路径>");
        docxFile = new File(scanner.nextLine());
        try{
            checkFileType(docxFile);
        }catch (FileNotFoundException e){
            System.out.println(e.getMessage());
        }
    }

    @Override
    public String toData() {
        try{
            FileInputStream inputStream = new FileInputStream(this.docxFile);
            docx = new XWPFDocument(inputStream);
            List<XWPFTable> tables = docx.getTables();
            return tables.get(1).getText();
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    private void checkFileType(File docxFile)throws FileNotFoundException{
        if(docxFile.isFile()){
            String fileName = docxFile.getName();
            int lastDot = fileName.lastIndexOf(".");
            if(lastDot < -1){
                throw new FileNotFoundException("未知文件");
            }
            String suffix = fileName.substring(lastDot+1);
            if("docx".equals(suffix)){
                return ;
            }else{
                throw new FileNotFoundException("非docx文件");
            }
        }else{
            throw new FileNotFoundException("非文件");
        }
    }
}
